﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    public class ReflectHelper
    {
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T">实例对象</typeparam>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="typeName">实例对象类型</param>
        /// <returns></returns>
        public static object CreateInstance(string assemblyName, string typeName)
        {
            try
            {
                return System.Reflection.Assembly.Load(assemblyName).CreateInstance(typeName);
            }
            catch
            {
                return default(object);
            }
        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T">实例对象</typeparam>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="typeName">实例对象类型</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string assemblyName, string typeName)
        {
            return (T)CreateInstance(assemblyName, typeName);
        }
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T">实例对象</typeparam>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="typeName">实例对象类型</param>
        /// <param name="param">实例参数</param>
        /// <param name="typeParam">实例参数类型</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string assemblyName, string typeName, object[] param, Type[] typeParam)
        {
            try
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(assemblyName);
                Type t = assembly.GetType(typeName, false, true);
                System.Reflection.ConstructorInfo constructor = t.GetConstructor(typeParam);
                return (T)Activator.CreateInstance(constructor.DeclaringType, param);
            }
            catch
            {
                return default(T);
            }
        }
    }
}
